package com.example.demo_service

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.demo_service.service.MyIntentService
import com.example.demo_service.service.MyService

/**
 * 1.startService：启动后一直运行，直到调用stopService停止，和调用者无关联
 *      onCreate-->onStartCommand-->onDestroy
 * 2.bindService：和调用者关联，调用service提供的方法
 *      onCreate-->onBind-->onUnbind-->onDestroy
 *
 * 3.混合使用
 *  onCreate-->onStartCommand->onBind-->onUnbind-->onDestroy
 *  启动：startService--》bindService
 *  停止：unbindService--》stopService
 *
 */
class MainActivity : AppCompatActivity() {
    companion object {
        const val TAG = "MainActivity"
    }
    private lateinit var intent:Intent
    private var binder:MyService.MyBinder? = null
    //和服务链接
    private val connection:ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Log.d(TAG, "onServiceConnected: ")
            binder = service as MyService.MyBinder
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            Log.d(TAG, "onServiceDisconnected: ")
        }

    }
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        intent = Intent(this, MyService::class.java)
    }

    fun startService(view: View) {
        startService(intent)
    }
    fun stopService(view: View) {
        stopService(intent)
    }
    fun bindService(view: View) {
        bindService(intent,connection, BIND_AUTO_CREATE)
    }
    fun unbindService(view: View) {
        unbindService(connection)
    }
    //调用服务的方法
    fun sum(view: View) {
        val sum = binder?.sum(10, 11)
        Log.d(TAG, "sum: $sum")
    }

    fun start2(view: View) {
        startService(intent)
        bindService(intent,connection, BIND_AUTO_CREATE)
    }
    fun stop2(view: View) {
        unbindService(connection)
        stopService(intent)
    }

    fun startIntentService(view: View) {
        val intent = Intent(this,MyIntentService::class.java)
        startService(intent)
    }
}